package com.central.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.central.common.exception.BizExceptionEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * 响应数据
 *
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Result<T> implements Serializable {
    private T data;
    private Integer resp_code;
    private String resp_msg;

    public static <T> Result<T> of(T data, Integer code, String msg) {
        return new Result<>(data, code, msg);
    }

    public static <T> Result<T> succeed(T model, String msg) {
        return of(model, BizExceptionEnum.SUCCESS.getCode(), msg);
    }

    public static <T> Result<T> succeed(T model) {
        return of(model, BizExceptionEnum.SUCCESS.getCode(), "");
    }

    public static Result<Map<String, Object>> succeedForKey(String key, Object model) {
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put(key, model);
        return of(resMap, BizExceptionEnum.SUCCESS.getCode(), "");
    }

    public static Result buildForResult(String key, Result result) {
        if (result.isFail() || StringUtils.isBlank(key)) {
            return result;
        }
        Map<String, Object> resMap = new HashMap<String, Object>();
        resMap.put(key, result.getData());
        return of(resMap, BizExceptionEnum.SUCCESS.getCode(), "");
    }

    public static <T> Result<T> failed(T model, String msg) {
        return of(model, BizExceptionEnum.SERVER_ERROR.getCode(), msg);
    }

    public static <T> Result failed(BizExceptionEnum exceptionEnum) {
        return of(null, exceptionEnum.getCode(), exceptionEnum.getMessage());
    }

    public static <T> Result<T> failed(String msg) {
        return of(null, BizExceptionEnum.SERVER_ERROR.getCode(), msg);
    }


    public static <T> Result<T> succeedWith(T data, Integer code, String msg) {
        return new Result<>(data, code, msg);
    }

    public static <T> Result<T> failedWith(T data, Integer code, String msg) {
        return new Result<>(data, code, msg);
    }

    @JsonIgnore
    public boolean isSuccess() {
        return BizExceptionEnum.SUCCESS.getCode().equals(this.resp_code);
    }

    @JsonIgnore
    public boolean isFail() {
        return !isSuccess();
    }
}
